﻿using System;
using System.ServiceModel;
using ExplorerService.Common.DataContracts.Operations;
using ExplorerService.Common.DataContracts.Operations.OperationProgress;
using ExplorerService.Common.ServiceContracts;
using ExplorerService.Managers;

namespace ExplorerService.Communication
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]   
    public class ApplicationOperationsService : IApplicationOperationsService
    {
        /// <summary>
        /// Returns the next available operation that needs to be performed by this application
        /// </summary>
        /// <param name="applicationSessionId">The application session ID</param>
        /// <returns>The next queued operation or Exception if the request is invalid</returns>
        public Operation GetNextOperation(Guid applicationSessionId)
        {
            if (!ApplicationSessionManager.Instance.ValidSessionId(applicationSessionId))
            {
                throw new Exception("Invalid application session ID");
            }

            OperationContext.Current.Channel.OperationTimeout = TimeSpan.FromHours(24);
            return OperationOrchestrator.Instance.NextOperation(applicationSessionId);
        }

        /// <summary>
        /// Posts the operation progress to the operation orchestrator
        /// </summary>
        public bool PostOperationProgress(Guid applicationSessionId, OperationProgress operationProgress)
        {
            if (!ApplicationSessionManager.Instance.ValidSessionId(applicationSessionId))
            {
                throw new Exception("Invalid application session ID");
            }
            OperationOrchestrator.Instance.HandleOperationProgress(operationProgress);
            return true;
        }

        /// <summary>
        /// Gets the cancel flag for the operation
        /// </summary>
        public bool CancelPending(Guid applicationSessionId, Guid operationId)
        {
            if (!ApplicationSessionManager.Instance.ValidSessionId(applicationSessionId))
            {
                throw new Exception("Invalid application session ID");
            }
            return OperationOrchestrator.Instance.OperationCancelPending(operationId);
        }
    }
}